﻿using iTool.Cloud.Center.Model;
using iTool.Cloud.Database;
using iTool.Cloud.Database.LocalServiceProvider;
using iTool.Cloud.DataSearch;
using iTool.ClusterComponent;

using Microsoft.Extensions.Configuration;

using Newtonsoft.Json;

var aISQLProvider = new AISQLProvider();
var xxx = aISQLProvider.GetAnalysisResult("select * from userxxx where search(must(name),shoube(tag),mustnot(productName),distmap(x,y), name, 'next',200) in ('%jian%','包吃','橘子',100,'xxx') order by sortdist(x,y) desc");
xxx = aISQLProvider.GetAnalysisResult("select * from userxxx where search(must(name),shoube(tag),mustnot(productName),distmap(x,y), name, 200) in ('%jian%','包吃','橘子',100,'xxx') order by sortdist(x,y) desc");
xxx = aISQLProvider.GetAnalysisResult("select * from userxxx where search(must(name),shoube(tag),mustnot(productName),distmap(x,y), name, 2,200) in ('%jian%','包吃','橘子',100,'xxx') order by sortdist(x,y) desc");
xxx = aISQLProvider.GetAnalysisResult("select * from userxxx where search(must(name),shoube(tag),mustnot(productName),distmap(x,y), name, null,200) in ('%jian%','包吃','橘子',100,'xxx') order by age,name desc");
xxx = aISQLProvider.GetAnalysisResult("select * from userxxx where search(must(name),shoube(tag),mustnot(productName),distmap(120.53,36.86,x,y), name,2,200) in ('%jian%','包吃','橘子',100,'xxx') order by age,name desc");

{
    //var test = new SqliteTest();
    //var trans = test.BeginTransaction();
    //var listData = CityGeoInfo.GetCityGeoInfos();
    //foreach (var item in listData)
    //{
    //    test.ExecuteNonQuery(item.ToString());
    //}
    //test.Commit(trans);

    //var resultvalue = test.ExecuteQuery("select distance(120.53,36.86,x,y) distance,* from users where distance(120.53,36.86,x,y) <= 200 order by distance(120.53,36.86,x,y) asc");
    //Console.WriteLine(resultvalue);
    //Console.Clear();

    SimpleGeoDirectory.Writer(CityGeoInfo.GetCityGeoInfos());
    SimpleGeoDirectory.Search(123.38, 41.8, 500);
}

//while (true)
//{
//    var input = Console.ReadLine();
//    if (input == null) continue;
//    SimpleDirectory.reader1(input);
//}

IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile(path: "appsettings.json", optional: true, reloadOnChange: true)
                .Build();

var builder = new iToolClientBuilder();

var clusterOptions = new ClusteringStaticOptions(
    new ServiceEndPointOptions(configuration, true),
    new ClusterIdentificationOptions(configuration, true));

builder.UseiCenterClustering(new ClusterIdentificationOptions(), clusterOptions);
var cluster = await builder.BuildAndConnectAsync();

// 分页，排序
// 分页2种， 一种sql分页。 2种自定义分页函数
// 默认排序，和 排序函数
// select *,distance(120.76,30.77,x,y) distance from shopProvider where search(name,tag) like '%打游戏%' and searchByGeo(x,y) <= 100 order by map(x,y) asc

// search(name,tag, size: 20)
// search(name,tag, page:1, size:20)
// search(name,tag, start:'key', size: 20)

var executor = cluster.GetSqlExecutor();

var countObj = 0;// (long)await executor.ExecuteScalarAsync("select count(1) from USERS");
//int.TryParse(countObj.ToString(), out int countRows);
if (countObj == 0)
{
    //var listData = CityGeoInfo.GetCityGeoInfos();
    //foreach (var item in listData)
    //{
    //    test.ExecuteNonQuery(item.ToString());
    //}

    await Parallel.ForEachAsync(CityGeoInfo.GetCityGeoInfos(), async (item,canceltoken) =>
    {
        await executor.ExecuteNonQueryNoResultAsync(item.ToString());
    });
}

Console.Clear();

while (true)
{
    var input = Console.ReadLine();
    if (string.IsNullOrWhiteSpace(input)) continue;
    if (input == "clear")
    {
        Console.Clear();
        continue;
    }

    DateTime old = DateTime.Now;
    Console.WriteLine("start:"+ old);
    if (input.StartsWith("select"))
    {
        //var lastResult = "";
        await Parallel.ForEachAsync(new byte[1], async (i, c) =>
        {
            try
            {
                var lastResult = await executor.ExecuteReaderAsync(input);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        });
        //Console.WriteLine(lastResult);
        //Console.WriteLine(lastResult.Length);

    }
    else if (input.StartsWith("t- select"))
    {
        input = input.Substring(3);
        object lastResult = null;
        await Parallel.ForEachAsync(new byte[1], async (i, c) =>
        {
            try
            {
                lastResult = await executor.ExecuteReaderAsync<UserTable>(input);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        });

        Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(lastResult, Formatting.Indented));
    }
    else if (input.StartsWith("begin:"))
    {
        input = input.Substring(6);
        var list = new List<iTool.Cloud.Database.Options.ExecuteItemOptions>();
        foreach (var sql in input.Split(';'))
        {
            list.Add(new iTool.Cloud.Database.Options.ExecuteItemOptions
            {
                Sql = sql
            });
        }

        await Parallel.ForEachAsync(new byte[1000], async (i, c) =>
        {
            //await executor.ExecuteTransactionAsync(list);
            await executor.ExecuteTransactionOfLockTableAsync(list);
        });

        
    }
    else
    {
        await Parallel.ForEachAsync(new byte[1], async (i, c) =>
        {
            try
            {
                var result = await executor.ExecuteNonQueryAsync(input);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        });
    }

    Console.WriteLine("end(s):" + (DateTime.Now - old).TotalMilliseconds);
    Console.WriteLine("end:" + DateTime.Now);


}

Console.ReadKey();